﻿namespace HuaWei.WinService
{
    using HuaWei;
    using System;
    using System.ComponentModel;
    using System.IO;
    using System.ServiceModel;
    using System.ServiceProcess;

    internal class Service : ServiceBase
    {
        private ServiceHost _host;
        private IContainer components;

        public Service()
        {
            this._host = null;
            this.components = null;
            this.InitializeComponent();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.components = new Container();
            base.ServiceName = "HWService";
        }

        protected override void OnContinue()
        {
            base.OnContinue();
        }

        protected override void OnPause()
        {
            try
            {
                if ((this._host != null) && ((this._host.State == CommunicationState.Opened) || (this._host.State == CommunicationState.Opening)))
                {
                    this._host.Close();
                    this.WriteLog("OnPause");
                }
            }
            catch (Exception exception)
            {
                this.WriteLog(exception.Message + "\n" + exception.StackTrace);
            }
            base.OnPause();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                if (this._host == null)
                {
                    this._host = new ServiceHost(typeof(WCFService), new Uri[0]);
                }
                this.WriteLog("OnStart");
                this._host.Open();
            }
            catch (Exception exception)
            {
                this.WriteLog(exception.Message + "\n" + exception.StackTrace);
            }
        }

        protected override void OnStop()
        {
            try
            {
                if ((this._host != null) && ((this._host.State == CommunicationState.Opened) || (this._host.State == CommunicationState.Opening)))
                {
                    this._host.Close();
                    this.WriteLog("OnStop");
                }
            }
            catch (Exception exception)
            {
                this.WriteLog(exception.Message + "\n" + exception.StackTrace);
            }
        }

        private void WriteLog(string log)
        {
            using (StreamWriter writer = new StreamWriter(@"d:\servicelog.txt", true))
            {
                writer.AutoFlush = true;
                writer.WriteLine(DateTime.Now.ToString("yyyy年MM月dd日HH:mm:ss:fff ") + log);
            }
        }
    }
}

